<%@ include file="header.jsp"%>

<table align="center" cellpadding="0" cellspacing="0" height="100%"
	width="100%" border="0">
	<tr>
		<td valign="top">
		<div id="scheduleDiv" />
		</td>
	</tr>
</table>

<script type="text/javascript">
var schedulePnl,pendingSchWin,scheduleGrid;

function formatDate(value){
	if(value instanceof Date){
		return value ? Ext.Date.dateFormat(value, 'Y/m/d') : '';
	}else{
		return value;
	}	
}

function initCalendar(){
	for(var i=1;i<6*7+1;i++){
		schedulePnl.add(Ext.create('Ext.panel.Panel',{
			xtype:'panel',
			id:'cPanel'+i,
			title:'a',
			layout:'vbox',
			forceFit:true,
			height:100
		}));
	}
}

function initListener(){
	for(var i=1;i<6*7+1;i++){
		var schedulePnl = Ext.getCmp('cPanel'+i);
		schedulePnl.getEl().on('dblclick',function(event,element,otps){
			selectModels(Ext.fly(event.getTarget()));
		});
	}	
}

function selectModels(comp){
	var yearCombo = Ext.getCmp('yearCombo');
	var monthCombo = Ext.getCmp('monthCombo');
	if(!pendingSchWin){
		scheduleGrid = Ext.create('Ext.grid.Panel',{
			border:0,
			id:'scheduleGrid',
			forceFit:true,
			autoScroll:true,
			enableColumnHide:false,
			enableColumnResize:false,
			sortableColumns:false,
			columnLines:true,
			enableColumnMove:false,
			autoHeight:true,
			region: 'center',
			columns:[{
				text:'Request No.',
				dataIndex:'requestNo',
				width:90
			},{
				text:'Sub Model Name',
				dataIndex:'modelName'
			},{
				text:'Project',
				columns:[{
					text:'Project No.',
					dataIndex:'projectNumber'
				},{
					text:'Project Name',
					dataIndex:'project'
				}]
			},{
				text:'Test Condition',
				columns:[{
					text:'Ignition<br>Time(s)',
					width: 80,
					dataIndex:'ignitionTime'
				},{
					text:'Storage<br>Time(h)',
					width:80,
					dataIndex:'storageTime',
					renderer: columnWrap
				},{
					text:'Duration(day)',
					dataIndex:'duration'
				}]
			},{
				text:'Start Date',
				dataIndex:'startDate',
				renderer: formatDate,
				editor: {
	                xtype: 'datefield',
	                format: 'Y/m/d',
					minValue:new Date()
	            }
			},{
				text:'End Date',
				dataIndex:'endDate',
				renderer: formatDate,
				editor: {
	                xtype: 'datefield',
	                format: 'Y/m/d',
					minValue:new Date()
	            }
			}],
			store:new Ext.data.Store({
		        autoLoad: false,
				fields:['orderId','requestNo', 'clientUniqueId','modelName','projectNumber', 'project','duration','ignitionTime','storageTime','startDate','endDate'],
				proxy: {
					type: 'ajax',
					url: 'getPendingSchedule.action',  // url that will load data with respect to start and limit params
					reader: {
						type: 'json',
						root: 'items',
						totalProperty: 'size'
					}
				}
			}),
			tbar:Ext.create("Ext.Toolbar", {
				items:[{
					xtype:'combo',
					fieldLabel:'Filter Criteria',
					id:'addCriteria',
					queryMode: 'local',
					labelWidth:100,
					width:230,
					valueField: 'value',
					displayField: 'text',
					store: new Ext.create('Ext.data.Store', {
						fields: ['value', 'text'],
						data: [
							{"value":"", "text":"--None--"},
							{"value":"trpNo", "text":"Trp No."},
							{"value":"prjNum", "text":"Project Number"},
							{"value":"prj", "text":"Project Name"}
						]
					}),
					value:""
				},{
					xtype:'textfield',
					id:'addValue',
					width:120
				},{
					xtype: 'button',
					text: 'Search',
					cls:'x-btn',
					listeners:{
						'click':function(){
							var scheduleGrid0 = Ext.getCmp('scheduleGrid');
							if(scheduleGrid0){
								scheduleGrid0.getEl().mask('loading...');
								scheduleGrid0.getStore().on('beforeload', function (store, options) {
									var new_params = {addCriteria: Ext.getCmp('addCriteria').getValue(), addValue:Ext.getCmp('addValue').getValue()};
									Ext.apply(store.proxy.extraParams, new_params);
								});
								scheduleGrid0.getStore().load();
								scheduleGrid0.getView().refresh();
							}
						}
					}
				}]
			}),
			plugins: Ext.create('Ext.grid.plugin.CellEditing', {
				clicksToEdit: 1
			})
		});
		scheduleGrid.getView().on('afterrender',function(){scheduleGrid.getEl().mask('loading...');});
		scheduleGrid.getView().on('refresh',function(){scheduleGrid.getEl().unmask();});
		pendingSchWin = Ext.create('Ext.Window', {
			title: 'Lab Schedule',
			autoScroll:false,
			width: 850,
			height: 500,
			border:0,
			modal:true,
			buttonAlign : "center",
			layout: 'border',
			defaults: {
				anchor: '100%'
			},
			items: [scheduleGrid],
			closeAction: function(){
				pendingSchWin.hide();
			},
			buttons:[{
				text:'Save',
				id:'btnSave',
				handler:function (){
					var store = scheduleGrid.getStore();
					if(store&&store.getCount()>0){
						var validate = true, orderIds='',clientUniqueIds='',startDates='',endDates='';
						for(var i=0;i<store.getCount();i++){
							var record = store.getAt(i);
							var startDate = record.data.startDate;
							var endDate = record.data.endDate;
							if((startDate==''&&endDate=='')||(!record.isModified('startDate')&&!record.isModified('endDate'))){
								continue;
							}else if(startDate==''||endDate==''){
								Ext.MessageBox.alert('Warning', 'Both Start Date and End Date need to be filled in.');
								validate = false;
								break;
							}else{
								orderIds+=record.data.orderId;
								clientUniqueIds+=record.data.clientUniqueId;
								startDates+=formatDate(record.data.startDate);
								endDates+=formatDate(record.data.endDate);
							}
						}
						if(validate){
							if(orderIds==''){
								Ext.MessageBox.alert('Warning', 'No data need to save.');
							}else{
								Ext.Ajax.request({
									url: 'UpdateScheduleTimeSlot.action',
									params: {
										orderIds:orderIds,
										clientUniqueIds:clientUniqueIds,
										startDates:startDates,
										endDates:endDates
									},
									success: function(response){
										flashMessage('data saved.','btnSave',1500);
										var yearCombo = Ext.getCmp('yearCombo');
										var monthCombo = Ext.getCmp('monthCombo');
										if(monthCombo&&yearCombo){
											var year = yearCombo.getValue();
											var month = monthCombo.getValue();
											loadSchedule(year,month);
										}	
									},
									failure: function(response){
										Ext.MessageBox.alert('Warning', 'Save data failed, please try again.');
									}
								});
							}
						}
					}
				}
			},{
				text:'Cancel',
				handler:function (){
					pendingSchWin.hide();
				}
			}]
		});
	}
	scheduleGrid.getStore().load();
	pendingSchWin.show();
}

function reDisplayCalendar(){
	schedulePnl.mask('loading...');
	var yearCombo = Ext.getCmp('yearCombo');
	var monthCombo = Ext.getCmp('monthCombo');
	if(monthCombo&&yearCombo){
		var year = yearCombo.getValue();
		var month = monthCombo.getValue();
		var date = new Date();
		date.setFullYear(year);
		date.setMonth(month-1);
		date.setDate(1);
		var weekday = date.getDay();
		var monthDays = new Date(year,month,0).getDate();
		var lines = 5;
		if(monthDays==28&&weekday==0){
			lines = 4;
		}else if((7-weekday)<(monthDays-28)){
			lines = 6;
		}
		
		var idx = 0;
		while(idx<weekday){
			var pnl = Ext.getCmp('cPanel'+(++idx));
			pnl.setTitle('');
			pnl.show();
			pnl.setDisabled(true);
		}
		for(var j=0;j<monthDays;j++){
			var pnl = Ext.getCmp('cPanel'+(++idx));
			pnl.setTitle((j+1)+'/'+month+'/'+year);
			pnl.show();
			pnl.setDisabled(false);
		}
		for(var k=monthDays+weekday+1;k<6*7+1;k++){
			var pnl = Ext.getCmp('cPanel'+(k));
			pnl.hide();
		}
	}
	loadSchedule(year,month);
}

function loadSchedule(year,month){
	Ext.Ajax.request({
		url: 'getScheduledData.action',
		params: {
			year:year,
			month:month
		},
		success: function(response){
			var ret = Ext.decode(response.responseText);
			if(ret){
				var idx,models;
				for(var i=1;i<43;i++){
					var pnl = Ext.getCmp('cPanel'+i);
					pnl.removeAll();
					if(pnl.title!=''){
						models=ret[pnl.title];
						if(models){
							for(var j=0;j<models.length;j++){
								pnl.add(Ext.create('Ext.form.Label',{
									html:'<div title="'+models[j]+'">'+models[j]+'</div>'
								}));
							}
						}
					}
				}	
			}
			schedulePnl.unmask();
		},
		failure: function(response){
			schedulePnl.unmask();
			Ext.MessageBox.alert('Warning', 'Schedule load failed, please try again.');
		}
	});
}

Ext.onReady(function(){
	if(!schedulePnl){
		schedulePnl = Ext.create('Ext.panel.Panel',{
			forceFit:true,
			frame:true,
			title:'Lab Schedule',
			id:'schedulePanel',
			layout: {
				type: 'table',
				columns: 7,
				tableAttrs: {
					border:1,
					bordercolor:'white',
					width:'100%'
				},
				tdAttrs:{
					align:'center',
					width:'14%'
				}
			},
			defaultType: 'label',
			items:[{
				xtype:'panel',
				frame:true,
				layout:'hbox',
				colspan:7,
				items:[{
					xtype:'combo',
					id:'yearCombo',
					fieldLabel:'Year',
					displayField: 'name',
					valueField: 'name',
					queryMode: 'local',
					editable:false,
					value:new Date().getFullYear(),
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=18',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					listeners:{
						'change':reDisplayCalendar
					}
				},{
					xtype:'combo',
					id:'monthCombo',
					fieldLabel:'Month',
					displayField: 'name',
					valueField: 'name',
					queryMode: 'local',
					editable:false,
					value:new Date().getMonth()+1,
					store:  Ext.create('Ext.data.Store', {
						autoLoad:true,
						fields: ['name'],
						proxy: {
							type: 'ajax',
							url: 'getList.action?listId=19',
							reader: {
								type: 'json',
								root: 'itemList',
								totalProperty: 'size'
							}
						}
					}),
					listeners:{
						'change':reDisplayCalendar
					}
				}]
			},{
				text:'Sunday'
			},{
				text:'Monday'
			},{
				text:'Tuesday'
			},{
				text:'Wednesday'
			},{
				text:'Thursday'
			},{
				text:'Friday'
			},{
				text:'Saturday'
			}]
		});
		initCalendar();
		schedulePnl.render('scheduleDiv');
		initListener();
	}
	reDisplayCalendar();
});

</script>

<%@ include file="footer.jsp"%>